var stopMarkers = []; // array of google.maps.Marker
var showStops = true;
var kml = null;

// url - url with KML data
function showPathOnMap(url) {
    clearMarkers();
    if (kml != null) {
        delete kml;
    }
    showStops = false;
    kml = new google.maps.KmlLayer(url);
    kml.setMap(mapContainer.map);
}

function showStopsForBounds() {    
    if (!showStops) {
        return;
    }
    clearMarkers();
    var bounds = mapContainer.map.getBounds();
    if (bounds == null) {
        return;
    }

    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    url = "http://transit.cloudapp.net/DevTransitODataService.svc/GeoAreas('" + roundNumber(ne.lat(), 7) + "%7C" + roundNumber(ne.lng(), 7) + "%7C" + roundNumber(sw.lat(), 7) + "%7C" + roundNumber(sw.lng(), 7) + "')/Stops?$format=json&$callback=?";
    $.getJSON(
        url,
        function (result) {
            if (result != null) {
                $.each(result.d, function () {
                    $.each(this, function () {
                        var position = new google.maps.LatLng(this.Lat, this.Lon);
                        addMarker(position);
                    });
                });
            }
        }
    );

    var addMarker = function (position) {
        var marker = new google.maps.Marker({
            map: mapContainer.map,
            position: position
        });
        google.maps.event.addListener(
	        marker,
		    'click',
		    function (event) { mapTapped(marker.getPosition()); }
        );
        stopMarkers.push(marker);
    };
}

function clearMarkers() {
    if (stopMarkers.length == 0)
        return;

    for (i = 0; i < stopMarkers.length; i++) {
        stopMarkers[i].setMap(null);
        delete stopMarkers[i];
    }
    stopMarkers = [];
}

function clearPathOnMap() {
    if (kml != null) {
        kml.setMap(null);
	showStops = true;
    }
}

function roundNumber(number, digits) {
    var multiple = Math.pow(10, digits);
    var rndedNum = Math.round(number * multiple) / multiple;
    return rndedNum;
}